<?php
/**
 *
 * @category   DDB
 * @package    Ddb_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2009 DDB
 * @version    $Id: FormHiddenDisplay.php 16541 2009-10-12 17:02:30Z tbrouard $
 */
/**
 * Abstract class for extension
 */
require_once 'Zend/View/Helper/FormElement.php';
/**
 * Helper to generate a "hidden" element
 *
 * @category   DDB
 * @package    Ddb_View
 * @subpackage Helper
 */
class Jnd_View_Helper_FormUploadJnd extends Zend_View_Helper_FormElement
{

    /**
     * Generates a 'hidden' element.
     *
     * @access public
     *
     * @param string|array $name If a string, the element name.  If an
     * array, all other parameters are ignored, and the array elements
     * are extracted in place of added parameters.
     * @param mixed $value The element value.
     * @param array $attribs Attributes for the element tag.
     * @return string The element XHTML. div tag + input hidden tag
     */
    public function formUploadJnd( $name, $value = null, array $attribs = null )
    {
        $info = $this->_getInfo($name, $value, $attribs);
        extract($info); // name, value, attribs, options, listsep, disable
        if (isset($id)) {
            if (isset($attribs) && is_array($attribs)) {
                $attribs['id'] = $id;
            } else {
                $attribs = array(
                    'id' => $id
                );
            }
        } else {
            $attribs['id'] = $name;
        }
        $attribs['name'] = $name;
        
        $defaultAttribs = array(
            'method' => "POST",
            'action' => array(
                'module' => 'default',
                'controller' => 'upload',
                'action' => 'upload',
                'complement' => ''
            ),
            'css' => array(
                'interne' => false, 
                'fichier' => 'jquery.fileupload-ui.css', 
                'chemin' => 'plugins/upload/blueimp/jQueryFileUpload/'
            )
        );
        
        $attribsUploadDdb = array_merge($defaultAttribs, $attribs);
        
        $view = Jnd_App::getResource("view");
        $jquery = Jnd_App::getConfig('jquery');
        $jqueryServeurUrl = $jquery['path']['min'];
        
        if ( $attribsUploadDdb['css']['interne'] ) {
            $urlCss = '/' . $attribsUploadDdb['css']['chemin'] . $attribsUploadDdb['css']['fichier'];
        } else {
            $urlCss = $jqueryServeurUrl . $attribsUploadDdb['css']['chemin'] . $attribsUploadDdb['css']['fichier'];
        }
        
        $selector = 'fileupload' . $name . '';
//        $selector = 'fileupload';
        
        $view->jQuery()
            ->addJavascriptFile($jqueryServeurUrl . 'plugins/upload/blueimp/jQueryFileUpload/jquery.fileupload.js')
            ->addJavascriptFile($jqueryServeurUrl . 'plugins/upload/blueimp/jQueryFileUpload/jquery.fileupload-ui.js')
            ->addJavascriptFile($jqueryServeurUrl . 'plugins/upload/blueimp/jQueryFileUpload/jquery.iframe-transport.js')
            ->addJavascriptFile($jqueryServeurUrl . 'plugins/upload/blueimp/jQueryFileUpload/jquery.tmpl.js')
            ->addStylesheet($urlCss);
        $view->jQuery()->addOnLoad("
        	$('#$selector').fileupload({});

            // Load existing files:
            $.getJSON($('#$selector form').prop('action'), function (files) {
                var fu = $('#$selector').data('fileupload');
                fu._adjustMaxNumberOfFiles(-files.length);
                fu._renderDownload(files)
                    .appendTo($('#$selector .files'))
                    .fadeIn(function () {
                        // Fix for IE7 and lower:
                        $(this).show();
                    });
            });
        
            // Open download dialogs via iframes,
            // to prevent aborting current uploads:
            $('#$selector .files a:not([target^=_blank])').live('click', function (e) {
                e.preventDefault();
                $('<iframe style=\"display:none;\"></iframe>')
                    .prop('src', this.href)
                    .appendTo('body');
            });
            
        ");
        
        $helper = new Zend_View_Helper_FormFile();
        $helper->setView($view);
        $attribs['multiple'] = true;
        $formFile = $helper->formFile("files[]", $attribs);
        
        $request = Jnd_App::getBootstrap()->getResource("FrontController")->getRequest();
        $action = $attribsUploadDdb['action'];
        $complement = $action['complement'];
        
        if ( strpos( $complement, "{") !== false ) {
            preg_match_all('/{[^>]+}/', $complement, $matches);
            foreach ( $matches as $match ) {
                $parametre = substr($match[0], 1, strlen($match[0])-2);
                $replaceMatch = $request->getParam(strtolower($parametre),'');
                $complement = str_replace($match, $replaceMatch, $complement);
            }
        }
        
        $html = '<div id="' . $selector . '" class="ui-widget">
    <form action="/' . $action['module'] . '/' .$action['controller'] . '/' . $action['action'] . $complement . '" method="POST" enctype="multipart/form-data">
        <div class="fileupload-buttonbar">
            <label class="fileinput-button">
                <span>' . __('Ajouter des fichiers') . '</span>
                ' . $formFile . '
            </label>
            <button type="submit" class="start">' . __("Lancer l'upload") . '</button>
            <button type="reset" class="cancel">' . __("Annuler l'upload") . '</button>
            <button type="button" class="delete">' . __("Supprimer les fichiers") . '</button>
        </div>
    </form>
    <div class="fileupload-content">
        <table class="files"></table>
        <div class="fileupload-progressbar"></div>
    </div>
</div>
<script id="template-upload" type="text/x-jquery-tmpl">
    <tr class="template-upload{{if error}} ui-state-error{{/if}}">
        <td class="preview"></td>
        <td class="name">${name}</td>
        <td class="size">${sizef}</td>
        {{if error}}
            <td class="error" colspan="2">Error:
                {{if error === \'maxFileSize\'}}File is too big
                {{else error === \'minFileSize\'}}File is too small
                {{else error === \'acceptFileTypes\'}}Filetype not allowed
                {{else error === \'maxNumberOfFiles\'}}Max number of files exceeded
                {{else}}${error}
                {{/if}}
            </td>
        {{else}}
            <td class="progress"><div></div></td>
            <td class="start"><button>Start</button></td>
        {{/if}}
        <td class="cancel"><button>Cancel</button></td>
    </tr>
</script>
<script id="template-download" type="text/x-jquery-tmpl">
    <tr class="template-download{{if error}} ui-state-error{{/if}}">
        {{if error}}
            <td></td>
            <td class="name">${name}</td>
            <td class="size">${sizef}</td>
            <td class="error" colspan="2">Error:
                {{if error === 1}}File exceeds upload_max_filesize (php.ini directive)
                {{else error === 2}}File exceeds MAX_FILE_SIZE (HTML form directive)
                {{else error === 3}}File was only partially uploaded
                {{else error === 4}}No File was uploaded
                {{else error === 5}}Missing a temporary folder
                {{else error === 6}}Failed to write file to disk
                {{else error === 7}}File upload stopped by extension
                {{else error === \'maxFileSize\'}}File is too big
                {{else error === \'minFileSize\'}}File is too small
                {{else error === \'acceptFileTypes\'}}Filetype not allowed
                {{else error === \'maxNumberOfFiles\'}}Max number of files exceeded
                {{else error === \'uploadedBytes\'}}Uploaded bytes exceed file size
                {{else error === \'emptyResult\'}}Empty file upload result
                {{else}}${error}
                {{/if}}
            </td>
        {{else}}
            <td class="preview">
                {{if thumbnail_url}}
                    <a href="${url}" target="_blank"><img src="${thumbnail_url}"></a>
                {{/if}}
            </td>
            <td class="name">
                <a href="${url}"{{if thumbnail_url}} target="_blank"{{/if}}>${name}</a>
            </td>
            <td class="size">${sizef}</td>
            <td colspan="2"></td>
        {{/if}}
        <td class="delete">
            <button data-type="${delete_type}" data-url="${delete_url}">Delete</button>
        </td>
    </tr>
</script>';
        
        return $html;
    }
}
